package cn.lyjuan.aliyun.mq.conf.java.dynamic;

import cn.lyjuan.aliyun.mq.conf.java.conf.consumer.AMQConsumer;
import cn.lyjuan.aliyun.mq.conf.java.conf.producer.AMQProducer;
import cn.lyjuan.aliyun.mq.conf.java.conf.MQUserCst;
import cn.lyjuan.aliyun.mq.conf.java.dynamic.consumer.MQConsumerDynamicImpl;
import cn.lyjuan.aliyun.mq.conf.java.dynamic.listener.MQListenerDynamicImpl;
import cn.lyjuan.aliyun.mq.conf.java.dynamic.producer.MQProducerDynamicImpl;
import com.aliyun.openservices.ons.api.MessageListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * 动态注册Bean到SpringBeanFactory中
 * 启动方法 init
 * Created by chad on 2016/10/13.
 */
public class DynamicRegisterUtils
{
    private static Logger log = LogManager.getLogger(DynamicRegisterUtils.class.getName());

    /**
     * 动态注册
     */
    public static void register(ConfigurableApplicationContext applicationContext,
                                String baseName, String proFilePath,
                                Class<? extends AMQProducer> producerClass,
                                Class<? extends AMQConsumer> consumerClass,
                                Class<? extends MessageListener> listenerClass)
    {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();

        // 加载MQUserCst
        MQUserCstDynamicImpl cstBean = new MQUserCstDynamicImpl(baseName, proFilePath);
        cstBean.register(beanFactory);

        String[] profiles = applicationContext.getEnvironment().getActiveProfiles();

        MQUserCst cst = (MQUserCst) applicationContext.getBean(baseName + MQUserCstDynamicImpl.NAME_SUFFIX);
        log.info("load {} succ", baseName + MQUserCstDynamicImpl.NAME_SUFFIX);

        if (!cst.isStart()) return;

        if (cst.getUserType() == MQUserCst.UserType.PRODUCER)
        {// 根据启动标识及类型 加载MQProducer
            MQProducerDynamicImpl producerBean = new MQProducerDynamicImpl(baseName, producerClass);
            producerBean.register(beanFactory);
            log.info("load {} succ", baseName + MQProducerDynamicImpl.NAME_SUFFIX);
        } else if (cst.getUserType() == MQUserCst.UserType.CONSUMER)
        {// 根据启动标识及类型 加载MQConsumer
            if (null == listenerClass)
                throw new RuntimeException("consumer must set MessageListener");
            // MessageListener
            MQListenerDynamicImpl listenerBean = new MQListenerDynamicImpl(baseName, listenerClass);
            listenerBean.register(beanFactory);

            MQConsumerDynamicImpl consumerBean = new MQConsumerDynamicImpl(baseName, consumerClass);
            consumerBean.register(beanFactory);
            log.info("load {} succ", baseName + MQConsumerDynamicImpl.NAME_SUFFIX);
        }
    }
}
